﻿using Newtonsoft.Json;
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using WebApp.Models;

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            SendMsg("ogd5o5MuXbIC0ateoTZUhunuFpFQ", "b3c03c1bb35ae808fefaf26eefe45340");
        }
        public static void SendMsg(string touser,string formId)
        {

            string accessToken = GetAccessToken();

            HttpClient client = new HttpClient();
            TemplateMessage templateMessage = new TemplateMessage();
            templateMessage.touser = touser;
            templateMessage.access_token = accessToken;
            templateMessage.form_id = formId;// "63f5083c2ed7603310b558858aa97bbc";
            templateMessage.page = "/pages/detail/detail?gohome=1&activityId=44";
            templateMessage.template_id = "2QRxIbW93VWwMn8d2oMvDkN1taFDCRd2B76r0TGuzjk";
            templateMessage.emphasis_keyword = "";
            templateMessage.data = new { keyword1 = new { value = "zj" }, keyword2 = new { value = "chouj" }, keyword3 = new { value = "2019-02-02" }, keyword4 = new { value = "所有奖项已抽完，点击查看中奖名单" } };

            HttpContent httpContent = new StringContent(JsonConvert.SerializeObject(templateMessage));
            httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");

            HttpResponseMessage response = client.PostAsync("https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=" + accessToken, httpContent).Result;
            string result = response.Content.ReadAsStringAsync().Result;
            client.Dispose();
            TemplateResult access = Newtonsoft.Json.JsonConvert.DeserializeObject<TemplateResult>(result);
            if (access.errcode == 0)
            {
            }
        }
        /// <summary>
        /// 微信接口凭证
        /// </summary>
        /// <returns></returns>
        private static string GetAccessToken()
        {
            HttpClient client = new HttpClient();
            HttpResponseMessage response = client.GetAsync("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wxb13f1f472d44116a&secret=e232ba725e59b96ff1affececda6944f").Result;
            string result = response.Content.ReadAsStringAsync().Result;
            client.Dispose();
            AccessModel access = Newtonsoft.Json.JsonConvert.DeserializeObject<AccessModel>(result);
            if (access != null && access.errcode == 0)
            {
                return access.access_token;
            }
            return "";
        }
    }
}
